<?php

namespace addons\mplogin\model;

use think\Model;

class BindUser extends Model
{
    // 表名
    protected $name = 'mplogin_user';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    // 追加属性
    protected $append = [

    ];

    public static function bind($openid, $user_id)
    {
        $find = self::getUser($openid);
        if ($find) {
            $find->user_id = $user_id;
            $find->save();
            return $find;
        } else {
            return self::create([
                "user_id"   => $user_id,
                "mp_openid" => $openid,
            ]);
        }
    }

    public static function getUser($openid)
    {
        return self::get(["mp_openid" => $openid]);
    }

    public function user()
    {
        return $this->hasOne("User", "id", "user_id")->field("id,username,nickname,password,avatar");
    }

    public static function getOpenid($admin_id)
    {
        return self::get(["user_id" => $admin_id]);
    }
}
